<template>
  <div>
    <el-switch
      v-model="draggableFlag"
      active-text="开启拖拽"
      inactive-text="关闭拖拽">
    </el-switch>
    <el-button v-if="draggableFlag" @click="batchSave()">批量保存</el-button>
    <el-button type="danger" @click="batchDelete()">批量删除</el-button>
    <el-tree :data="menus"
             :props="defaultProps"
             @node-click="handleNodeClick"
             :expand-on-click-node="false"
             show-checkbox
             node-key="catId"
             :default-expanded-keys="defaultExpandedKeys"
             :draggable="draggableFlag"
             :allow-drop="allowDrop"
             @node-drop="handleDrop"
             ref="categoryTree"
    >
        <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)">
            Append
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            Delete
          </el-button>
           <el-button
             type="text"
             size="mini"
             @click="() => edit(node, data)">
            修改
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  export default {
    name: 'category',
    data () {
      return {
        category: {
          catId: null,
          name: '',
          parentCid: 0,
          catLevel: 0,
          showStatus: 1,
          icon: '',
          productUnit: '',
          sort: 0
        },
        maxLevel: 1,
        pCid: [],
        draggableFlag: false,
        menus: [],
        dialogVisible: false,
        dialogType: '',
        dialogTitle: '',
        updateNodes: [],
        defaultExpandedKeys: [],
        defaultProps: {
          children: 'child',
          label: 'name'
        }
      }
    },
    methods: {
      batchDelete () {
        let checkedNodes = this.$refs.categoryTree.getCheckedNodes(false, false)
        // console.log(checkedNodes)
        let catIds = []
        let catNames = []
        for (let i = 0; i < checkedNodes.length; i++) {
          catIds.push(checkedNodes[i].catId)
          catNames.push(checkedNodes[i].name)
        }
        this.$confirm(`是否删除【${catNames}】菜单?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(catIds, false)
          }).then(({data}) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getDataList()
            // this.defaultExpandedKeys = [node.parent.data.catId]
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      batchSave () {
        this.$http({
          url: this.$http.adornUrl('/product/category/updateBatch'),
          method: 'post',
          data: this.$http.adornData(this.updateNodes, false)
        }).then(({data}) => {
          this.$message({
            type: 'success',
            message: '更新成功!'
          })
          this.getDataList()
          this.defaultExpandedKeys = this.pCid
          // 重置 防止拖拽问题
          this.maxLevel = 0
          this.updateNodes = []
          // this.pCid = 0
        })
      },
      handleDrop (draggingNode, dropNode, dropType, ev) {
        console.log('tree drop: ', dropNode.label, dropType)
        // 1.当前节点的父节点
        let pCid = 0
        let brothers = null
        if (dropType === 'before' || dropType === 'after') { // 有可能拖成一级菜单 ，没有父节点
          pCid = dropNode.parent.data.catId === undefined ? 0 : dropNode.parent.data.catId
        } else {
          pCid = dropNode.data.catId
        }
        this.pCid.push(pCid)
        // 2.当前节点的排序
        if (dropType === 'before' || dropType === 'after') {
          brothers = dropNode.parent.childNodes
        } else {
          brothers = dropNode.childNodes
        }
        console.log('brothers')
        console.log(brothers)
        for (let i = 0; i < brothers.length; i++) {
          // 如果遍历的是当前正在拖拽的节点
          if (brothers[i].data.catId === draggingNode.data.catId) {
            let catLevel = draggingNode.data.catLevel
            if (brothers[i].level !== draggingNode.level) {
              // 当前节点的层级发生了变化
              catLevel = dropNode.level
              // 递归修改子节点
              this.updateChildNodeLevel(brothers[i].level)
            }
            this.updateNodes.push({catId: brothers[i].data.catId, sort: i, parentCid: pCid, catLevel})
          } else {
            this.updateNodes.push({catId: brothers[i].data.catId, sort: i})
          }
        }
        // 3.当前节点的层级
        console.log(this.updateNodes)
      },
      updateChildNodeLevel (node) {
        if (node.childNodes > 0) {
          for (let i = 0; i < node.childNodes.length; i++) {
            let cNode = node.childNodes[i].data
            this.updateNodes.push({ catId: cNode.data.catId, catLevel: node.childNodes[i].level })
            this.updateChildNodeLevel(cNode)
          }
        }
      },
      allowDrop (draggingNode, dropNode, type) {
        // 判断被拖动的当前节点层数 + 所在父节点的层级 不能大于3
        this.countLevel(draggingNode)
        let deep = Math.abs(this.maxLevel - draggingNode.level) + 1
        // console.log(deep)
        if (type === 'inner') {
          return (deep + dropNode.level <= 3)
        } else {
          return (deep + dropNode.parent.level) <= 3
        }
      },
      countLevel (node) {
        if (node.childNodes != null && node.childNodes.length > 0) {
          for (let i = 0; i < node.childNodes.length; i++) {
            if (node.childNodes[i].catLevel > this.maxLevel) {
              this.maxLevel = node.childNodes[i].catLevel
            }
            this.countLevel(node.childNodes[i])
          }
        }
      },
      addCategory () {
        console.log('addCategory ...')
        console.log(this.category)
        this.$http({
          url: this.$http.adornUrl('/product/category/save'),
          method: 'post',
          data: this.$http.adornData(this.category, false)
        }).then(({data}) => {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.dialogVisible = false
          this.getDataList()
        })
      },
      editCategory () {
        console.log('editCategory ...')
        console.log(this.category)
        let { catId, name, icon, productUnit } = this.category
        this.$http({
          url: this.$http.adornUrl('/product/category/update'),
          method: 'post',
          data: this.$http.adornData({ catId, name, icon, productUnit }, false)
        }).then(({data}) => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.dialogVisible = false
          this.defaultExpandedKeys = [this.category.parentCid]
          this.getDataList()
        })
      },
      append (data) {
        this.dialogTitle = '添加分类'
        this.dialogType = 'add'
        this.category.parentCid = data.catId
        this.category.catLevel = data.catLevel * 1 + 1
        this.category.catId = null
        this.category.name = ''
        this.category.icon = ''
        this.category.productUnit = ''
        this.category.showStatus = 1
        console.log(data.catLevel)
        console.log('append ...')
        this.dialogVisible = true
        this.getDataList()
        this.defaultExpandedKeys = [this.category.parentCid]
      },
      remove (node, data) {
        let ids = [data.catId]
        this.$confirm(`是否删除【${data.name}】类目?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            console.log('删除成功！')
            this.getDataList()
            this.defaultExpandedKeys = [node.parent.data.catId]
          })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      edit (node, data) {
        // 发送请求 拿到最新的数据
        this.$http({
          url: this.$http.adornUrl('/product/category/info/' + data.catId),
          method: 'get',
          params: this.$http.adornData({})
        }).then(({data}) => {
          this.category.catId = data.data.catId
          this.category.name = data.data.name
          this.category.icon = data.data.icon
          this.category.productUnit = data.data.productUnit
          this.category.parentCid = data.data.parentCid
          this.dialogVisible = true
          this.dialogType = 'edit'
          this.dialogTitle = '编辑分类'
          console.log(data.data)
        })
      },
      submitData () {
        if (this.dialogType === 'add') {
          this.addCategory()
        }
        if (this.dialogType === 'edit') {
          this.editCategory()
        }
      },
      // 获取数据列表
      getDataList () {
        this.$http({
          url: this.$http.adornUrl('/product/category/tree'),
          method: 'get'
        }).then(({data}) => {
          this.menus = data.data
          console.log(data.data)
        })
      },
      handleNodeClick (data) {
        console.log(data)
      }
    },
    created () {
      this.getDataList()
    }
  }
</script>

<style scoped>

</style>
